import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, Space, Divider } from 'antd';
import FormCondition from '@/components/FormCondition';
import PopImgShow from '@/components/PopImgShow';
import { connect, history } from 'umi';
import { Button, Row, Col } from 'antd';
import './index.less'
import { backgroundObj } from '@/utils/utils';
import CommentAnswerModal from '../CommentAnswerModal'
const MessageAnswerModal = (props) => {
    const { visible = false, onClose, loading, dispatch, handleCallback } = props;
    const { show = false, detail = {} } = visible;
    const { id, text } = detail
    const [list, setList] = useState([])
    const [total, setTotal] = useState(0)
    const [visibleComment, setVisibleComment] = useState(false)
    const [page, setPage] = useState({
        page: 1,
        limit: 20
    })
    const [loadingMore, setLoadingMore] = useState(false); // 新增加载更多状态
    const containerRef = useRef(null); // 滚动容器引用

    const fetchData = () => {
        setLoadingMore(true);
        dispatch({
            type: 'answering/fetchListUserHelpQaAnswerForAdmin',
            payload: {
                ...page,
                userHelpQaId: id
            },
            callback: (e, count) => {
                setList(prevList => [...prevList, ...e]); // 使用函数式更新确保数据正确合并
                setTotal(count);
                setLoadingMore(false);
            }
        })
    }

    // 处理滚动事件
    const handleScroll = () => {
        const container = containerRef.current;
        if (!container) return;

        // 滚动到底部判断（距离底部50px视为触底）
        const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;

        if (isAtBottom && !loadingMore && list.length < total) {
            // 更新页码并获取数据
            setPage(prevPage => ({
                ...prevPage,
                page: prevPage.page + 1
            }));
        }
    };

    useEffect(() => {
        if (show) {
            fetchData()
        }
        else {
            setPage({
                page: 1,
                limit: 20
            })
            setList([])
        }
    }, [show])

    // 监听页码变化
    useEffect(() => {
        if (page.page > 1 && show) {
            fetchData();
        }
    }, [page.page]); // 当页码变化时加载数据

    // 添加滚动监听
    useEffect(() => {
        const container = containerRef.current;
        if (show && container) {
            container.addEventListener('scroll', handleScroll);
        }
        return () => {
            if (container) {
                container.removeEventListener('scroll', handleScroll);
            }
        };
    }, [show, loadingMore, list, total]);

    const modalProps = {
        title: '回答详情',
        width: 800,
        visible: show,
        maskClosable: true,
        destroyOnClose: true,
        zIndex: 1001,
        confirmLoading: loading,
        footer: null, // 隐藏默认底部按钮
    };

    return (
        <Modal {...modalProps} onCancel={onClose} >
            <div
                ref={containerRef}
                style={{ maxHeight: '640px', overflowY: 'auto', }}
                className='MutualList_box'
            >
                <div className='MutualList_question_name'>
                    {text}
                </div>
                {list.map((val, index) => {
                    const { content,
                        username,
                        userProfile,
                        createTime,
                        likeAmount,
                        collectAmount,
                        commentAmount
                    } = val
                    const {
                        text: answerText,
                        images,
                    } = JSON.parse(content)
                    const imageList = images ? images.split(',') : []
                    return (
                        <div key={index} className='MutualList_item_box'>
                            <div className='MutualList_item_user'>
                                <div style={backgroundObj(userProfile)} className='MutualList_item_profile'></div>
                                <div className='MutualList_item_title'>{username}</div>
                            </div>
                            <div className='MutualList_item_desc'>
                                {answerText}
                            </div>
                            <div className='MutualList_item_ImageBox'>
                                {imageList.map((img, imgIndex) => (
                                    <PopImgShow key={imgIndex} url={img} />
                                ))}
                            </div>
                            <div className='MutualList_item_time'>
                                <div className=''>
                                    {createTime}
                                </div>
                                <div className='MutualList_item_right'>
                                    <div className='MutualList_item_rightBox'>
                                        <div className='MutualList_item_rightBoxIcon1'></div>
                                        <div className=''>{likeAmount}</div>
                                    </div>
                                    <div className='MutualList_item_rightBox'>
                                        <div className='MutualList_item_rightBoxIcon2'></div>
                                        <div className=''>{collectAmount}</div>
                                    </div>
                                    <div className='MutualList_item_rightBox'>
                                        <div className='MutualList_item_rightBoxIcon3'></div>
                                        <div className=''>{commentAmount}</div>
                                    </div>
                                </div>
                            </div>
                            <div onClick={() => {
                                setVisibleComment({ show: true, detail: val })
                            }} style={{ cursor: 'pointer', color: '#1890ff', marginTop: 12 }} type='link'>查看评论详情</div>
                            <Divider />
                        </div>
                    )
                })}

                {/* 加载更多提示 */}
                {loadingMore && (
                    <div style={{ textAlign: 'center', padding: '10px' }}>
                        加载中...
                    </div>
                )}
                {!loadingMore && list.length >= total && total > 0 && (
                    <div style={{ textAlign: 'center', padding: '10px', color: '#999' }}>
                        没有更多数据了
                    </div>
                )}
            </div>
            <CommentAnswerModal visible={visibleComment} onClose={() => { setVisibleComment(false) }}></CommentAnswerModal>
        </Modal >
    );
};

export default connect(({ order, loading }) => ({
    loading: loading.effects['answering/fetchListUserHelpQaAnswerForAdmin'],
}))(MessageAnswerModal);